package com.ishopping.common.core.base.controller;

import com.ishopping.common.core.utils.date.DateUtils;
import com.ishopping.common.core.utils.security.StringEscapeEditor;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.sql.Timestamp;
import java.util.Date;


/**
 * 基础controller
 */
public abstract class BaseController {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		// String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
		binder.registerCustomEditor(String.class, new StringEscapeEditor() {
			@Override
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
			}
			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});

		// Date 类型转换
		binder.registerCustomEditor(Date.class, new StringEscapeEditor() {
			@Override
			public void setAsText(String text) {
				setValue(DateUtils.parseDate(text));
			}
		});

		// Timestamp 类型转换
		binder.registerCustomEditor(Timestamp.class, new StringEscapeEditor() {
			@Override
			public void setAsText(String text) {
				Date date = DateUtils.parseDate(text);
				setValue(date==null?null:new Timestamp(date.getTime()));
			}
		});
	}

}
